package com.lee.utils;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.MetaException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * @author lee
 * 弃用,直接使用hive jdbc 获取元数据
 */
public class MetaStoreUtils {

    public static HashMap<String, List<String>> getHiveAllTables() throws Exception {

        HiveConf hiveConf = new HiveConf();
//        hiveConf.addResource("hive-site.xml");
        hiveConf.set("hive.metastore.uris", PropertiesUtil.getValue("hive.metastore"));

        HiveMetaStoreClient client = new HiveMetaStoreClient(hiveConf);

        List<String> allDatabases = client.getAllDatabases();

        // 配置文件获取数据库列表，如果没有，则查询所有数据库
        List<String> databaseFromPro = MetaStoreUtils.getDatabaseFromPro();

        if(databaseFromPro!=null){
            allDatabases.clear();
           // 集合元素复制到另外一个集合
            allDatabases.addAll(databaseFromPro);
        }

        HashMap<String, List<String>> map = new HashMap<String, List<String>>();

        for (String allDatabase : allDatabases) {
            List<String> tablesList = client.getAllTables(allDatabase);
            map.put(allDatabase, tablesList);
        }
        return map;
    }

    public static HiveMetaStoreClient getMetastoreClient() throws MetaException {
        HiveConf hiveConf = new HiveConf();
//        hiveConf.addResource("hive-site.xml");
        hiveConf.set("hive.metastore.uris", PropertiesUtil.getValue("hive.metastore"));
        return new HiveMetaStoreClient(hiveConf);
    }

    public static List<String> getDatabaseFromPro() {

        String database = PropertiesUtil.getValue("database");
        if (!database.equals("")) {

            if (!database.contains(",")) {
                ArrayList<String> databaseList = new ArrayList<>();
                databaseList.add(database);

                return databaseList;
            } else {
                String[] split = database.split(",");
                List<String> strings = Arrays.asList(split);
                return strings;
            }
        }
        return null;
    }

    public static void main(String[] args) throws Exception {

        HiveMetaStoreClient metastoreClient = getMetastoreClient();
        HashMap<String, List<String>> hiveAllTables = MetaStoreUtils.getHiveAllTables();


    }

}
